package com.ywl5320.myplayer.codec;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.ywl5320.myplayer.util.WlCodecSupportUtil;

import java.io.IOException;
import java.nio.ByteBuffer;

import static android.content.ContentValues.TAG;

/**
 * Created by Chen qin lang on 2018/7/17.
 */
public class WlMediaCodec {

    private MediaCodec mediaCodec;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void init(String mime, int width, int height, byte[] csd_0, byte[] csd_1) {
        if (mime != null && width > 0 && height > 0) {

            try {
                String mimeType = WlCodecSupportUtil.findSupportCodec(mime);
                MediaFormat mediaFormat = MediaFormat.createVideoFormat(mimeType, width, height);
                mediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width * height);
     /*           mediaFormat.setInteger(MediaFormat.KEY_WIDTH, width);
                mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, height);*/
                mediaFormat.setByteBuffer("csd-0", ByteBuffer.wrap(csd_0));
                mediaFormat.setByteBuffer("csd-1", ByteBuffer.wrap(csd_1));
                Log.e(TAG, "init: " + mediaFormat.toString());
                mediaCodec = MediaCodec.createDecoderByType(mimeType);
                mediaCodec.configure(mediaFormat, null, null, 0);
                mediaCodec.start();
                Log.e(TAG, "init: " );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void feedMediaData(byte []media_data, int size) {
        Log.e(TAG, "feedMediaData: "+size );
        int buffInder = mediaCodec.dequeueInputBuffer(10);
        if (buffInder > 0) {
            ByteBuffer byteBuffer = mediaCodec.getInputBuffers()[buffInder];
            byteBuffer.clear();
            byteBuffer.put(media_data);
            mediaCodec.queueInputBuffer(buffInder, 0, size, 0, 0);

        }
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int dequeueIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10);//取出队列中的数据
        while (dequeueIndex >= 0) {
            mediaCodec.releaseOutputBuffer(dequeueIndex, true);
            dequeueIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10);//取出队列中的数据
        }
    }
}
